#include <stdio.h>
#include <stdint.h>
#include "sys_app.h"
#include "esp_log.h"
#include "msg_manager.h"
#include "sys_main.h"

#define TAG "SYS_MAIN"

sys_main_data_t* sys_main_data;

sys_main_data_t* sys_main_get_data(void)
{
    return sys_main_data;
}

static int sys_main_task_init(void)
{
    sys_main_data = malloc(sizeof(sys_main_data_t));
    if (sys_main_data == NULL) {
        ESP_LOGE(TAG, "sys_main_data malloc failed");
        return -1;
    }

    msg_manager_init();

    sys_main_view_init(MAIN_VIEW);

    return 0;
}

static void sys_main_task_exit(void)
{
    msg_manager_deinit();

    sys_main_view_exit(MAIN_VIEW);

    free(sys_main_data);
    sys_main_data = NULL;
}

void sys_main_task(void *pvParameters)
{
    ESP_LOGI(TAG, "sys_main_task start");

    struct app_msg* msg = NULL;

    if (sys_main_task_init()) {
        ESP_LOGE(TAG, "sys_main_task_init failed");
        return;
    }

    while (1) {
        if (msg_manager_receive_msg(&msg, portMAX_DELAY)) {
            ESP_LOGI(TAG, "%s: receive msg type: %d, cmd: %d, value: %08x", __func__, msg->type, msg->cmd, msg->value);
            switch (msg->type) {
                case MSG_KEY_INPUT:
                    sys_key_input_handler(msg->value);
                    break;

                case MSG_UI_EVENT:
			        ui_message_dispatch(msg->sender, msg->cmd, msg->value);
			        break;

                case MSG_INPUT_EVENT:
                    
                    break;

                case MSG_HOTPLUG_EVENT:
			        sys_main_hotplug_event_handle(msg);
			        break;

                default:
                    ESP_LOGW(TAG, "Unknown message type: %d", msg->type);
                    break;
            }
            msg_manager_receive_exit(msg);
        }
    }
    sys_main_task_exit();
}
